<?php
/**
 *
 * User: konakona http://www.crazyphper.com
 * Date: 13-5-19
 * Time: 下午10:42
 */
class CommonAction extends Action
{

	protected $id; //每个控制器里，当前操作的主PK值

	protected $curModel = null; //当前控制器专用模型

	protected $uid = 0;
	protected $username = "";

	protected $options = array();

	/**
	 * 分店ID
	 * 为0，则代表总店
	 * @var int
	 */
	public $bossID = 0;

	public function _initialize()
	{
//		dump(strstr($_SERVER['HTTP_USER_AGENT'],'Mobile'));
		if(!strstr($_SERVER['HTTP_USER_AGENT'],'Mobile') && C('APP_STATUS') != 'debug'){
			header('Location: http://www.crazyphper.com');
			die();
		}
		import('@.ORG.Util.Cookie');
		cookie('_currentUrl_', __SELF__);
		$this->curModel = D(MODULE_NAME);
		$this->id = $this->_request($this->curModel->getPk()) > 0 ? $this->_request($this->curModel->getPk()) : 0;
		$this->getWebSiteOptions();

		if ($this->getActionName() != 'Register' && $this->getActionName()!='Login' && $this->getActionname() !="Index")
		{
			//必须用户注册才可继续访问
			if ($this->onlineStatus() === false)
			{
//				$this->error("请您先填写注册信息，再继续访问", U('Register/index'));
				$this->error("请您先登录！", U('Login/index'));
			}
		}


		//在首页确定分店来源！
		if ($this->getactionName() == 'Index')
		{
			if (isset($_GET['bossID'])) //如果有分店请求
			{
				$bossInfo = D('Boss')->find($_GET['bossID']);
				if ($bossInfo)
				{
					if ($bossInfo['main_page'] == "")
					{
						die("您还没有设置首页模板！不能访问……");
					}
					$this->bossID = $_SESSION['bossID'] = $bossInfo['id'];
					$_SESSION['defaultMainpage'] = $bossInfo['main_page'];
					//剩下的虽然没用到，但是可能会有一天用到，所以放session里了！
					$_SESSION['bossName'] = $bossInfo['name'];
					$_SESSION['phone'] = $bossInfo['phone'];
					$_SESSION['address'] = $bossInfo['address'];
				} else
				{
					$this->error("您所访问的店面不存在！");
				}
			}
		}
		if (isset($_SESSION['bossID']))
		{
			$this->bossID = $_SESSION['bossID'];
		}

//		echo '您本次访问的店铺ID是:'.$this->bossID;
		$this->getUserInformation();
        $this->assign('boss_id',$this->bossID);


        //订单自动成功
        import('@.ORG.Util.OrderSuccess');
        OrderSuccess::run();

	}

	/**
	 * 检测当前SESSION中是否有用户在线
	 */
	protected function onlineStatus()
	{
		if ($_SESSION['user'])
		{
			//获得用户信息
			$this->uid = $_SESSION['user']['uid'];
			$this->username = $_SESSION['user']['username'];
		}else{
			return false;
		}
	}

	/**
	 * 获得网站配置
	 * 并导入模板变量
	 */
	protected function getWebSiteOptions()
	{
		$result = M('Options')->field('id', true)->select();

		$list = array();
		foreach ($result as $k => $v)
		{
			$list[$v['key']] = $v['value'];
		}
		$this->options = $list;
		$this->assign('options', $this->options);
	}

	/**
	 * 获得注册过这家店的用户的详细信息
	 */
	protected function getUserInformation() {
		if ($_SESSION['user'])
		{
			//获得用户信息
			$this->assign('user', $_SESSION['user']);
			$this->uid = $_SESSION['user']['id'];
			$this->username = $_SESSION['user']['phone'];
		}else{
			return false;
		}

	}

	/**
	 * 获得当前分店的信息
	 */
	protected function getBossInformation() { }

	/**
	+----------------------------------------------------------
	 * 取得操作成功后要返回的URL地址
	 * 默认返回当前模块的默认操作
	 * 可以在action控制器中重载
	+----------------------------------------------------------
	 * @access public
	+----------------------------------------------------------
	 * @return string
	+----------------------------------------------------------
	 * @throws ThinkExecption
	+----------------------------------------------------------
	 */
	function getReturnUrl()
	{
		return __URL__ . '?' . C('VAR_MODULE') . '=' . MODULE_NAME . '&' . C('VAR_ACTION') . '=' . C('DEFAULT_ACTION');
	}


	/*
* 分页方法,配合dwz呈现分页样式
* 并不需要再去计算复杂的分页层级、列表，这一切由dwz实现
* php只需要提供：总数、每页显示数、当前页数即可
* @param 总记录数
* @param 一页显示数量
* return obj
*/
	protected function _page($count = 0, $num = 0, $isDialog = false)
	{
		import('@.ORG.Util.MyPage');
		if ($count == 0 && $num == 0) $page = new MyPage($this->curModel->count(), C('PAGE_LIMIT'), $this->view, $isDialog); else
			$page = new MyPage($count, $num == 0 ? C('PAGE_LIMIT') : $num, $this->view, $isDialog);
		$this->assign('page', $page->show());
		return $page;
	}

	/**
	+----------------------------------------------------------
	 * 默认删除操作
	 * 当表结构中存在status时，将内容状态设置为禁用（status = 0 ）
	 * 当表结构中不存在status时，则彻底删除这条记录
	+----------------------------------------------------------
	 * @access public
	+----------------------------------------------------------
	 * @return string
	+----------------------------------------------------------
	 * @throws ThinkExecption
	+----------------------------------------------------------
	 */
	public function delete()
	{
		//删除指定记录
		if (!empty($this->curModel))
		{
			$pk = $this->curModel->getPk();
			$id = $_REQUEST [$pk];
			if (isset($id))
			{
				$condition = array($pk => array('in', explode(',', $id)));
				$result = $this->curModel->where($condition)->delete();

				if ($result !== false)
				{
					$this->success('删除成功！');
				} else
				{
					$this->error('删除失败！');
				}
			} else
			{
				$this->error('非法操作');
			}
		}
	}


	/**
	 * 立即发送订单清单至邮件！
	 * @param $orderID
	 * @param $content 如果有這個值則代表純文字預訂
	 */
	public function sendOrderMail($orderID,$content = '')
	{
		if ($content=="")
		{ //本站訂單預訂
			//獲得訂單信息拼湊成內容，然後發送
//			$shop = D('ShopCart')->where(array('order_id'=>$orderID))->select();
////			$ids = "";
//			foreach($shop as $k=>$v){
//				$ids[] = $v[''];
//			}
			$this->sendMail('有顧客下文字訂單啦', '請盡快到網站查閱！');
		} else
		{ //本站純文字預訂
			$this->sendMail("有顧客下文字訂單啦！",$content);
		}
	}

    /**
     * 发送取消订单邮件
     * @param $orderID
     */
    public function sendCancelOrderMail($orderID){}

	protected function sendMail($title, $content)
	{
		require_once(realpath('.') .'/'. APP_PATH . 'Lib/ORG/COM/PHPMailer_v5.1/class.phpmailer.php');
		if (false === class_exists('PHPMailer'))
		{
			$this->error("服務器發信設備有問題！管理員現在無法接受訂單預訂！請致電聯繫管理員！");
		}

		$mail = new PHPMailer();

		$content = str_replace("[\]", '', $content);

		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
		// 1 = errors and messages
		// 2 = messages only
		$mail->SMTPAuth = true; // enable SMTP authentication
		$mail->Host = $this->options['email_server']; // sets the SMTP server
		$mail->Port = $this->options['email_port']; // set the SMTP port for the GMAIL server
		$mail->Username = $this->options['email_account']; // SMTP account username
		$mail->Password = $this->options['email_passwd']; // SMTP account password

		$mail->SetFrom('unknow@qq.com', '便利店新消息');

		$mail->AddReplyTo('unknow@qq.com', '便利店新消息');

		$mail->Subject = $title;

//		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

		$mail->MsgHTML($content);

		$address = $this->options['system_email'];
		$mail->AddAddress($address, "Myself");

		if (!$mail->Send())
		{
//			echo "Mailer Error: " . $mail->ErrorInfo;
			return false;
		} else
		{
			return true;

		}
	}
}
